package cn.mg.framework.version;


import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author hezhaoming
 * @date 2020/5/13
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class AppRequestUtils {

    /**
     * 匹配路径中的版本号
     */
    public final static Pattern VERSION_PATTERN = Pattern.compile("/v(\\d+).(\\d+).(\\d+)/");

    /**
     * 检验版本号是否合法
     */
    public final static Pattern VERSION_NUMBER_PATTERN = Pattern.compile("(\\d+).(\\d+).(\\d+)");

    /**
     * Header中的api版本控制
     */
    public final static String VERSION_HEADER_PARAM = "api-Version";

    /**
     * Header中的app版本控制
     */
    public final static String APP_VERSION_HEADER_PARAM = "app-version";

    /**
     * Header中的版本控制
     */
    public final static String PLATFORM_HEADER_PARAM = "platform";

    public static String apiVersion(HttpServletRequest request) {
        return version(request, VERSION_HEADER_PARAM);
    }

    public static String appPlatform(HttpServletRequest request) {
        String appPlatform = (String) request.getAttribute(PLATFORM_HEADER_PARAM);
        if (StringUtils.isEmpty(appPlatform)) {
            appPlatform = request.getHeader(PLATFORM_HEADER_PARAM);
        }
        return appPlatform;
    }


    public static String version(HttpServletRequest request, String versionParam) {
        String apiVersion = null;
        //优先匹配路径,再从Header中获取
        Matcher m = VERSION_PATTERN.matcher(request.getRequestURI());
        if (m.find()) {
            apiVersion = m.group();
        } else {
            apiVersion = request.getHeader(versionParam);
        }
        if (StringUtils.isEmpty(apiVersion)) {
            return null;
        }
        //版本号是否合法
        m = VERSION_NUMBER_PATTERN.matcher(apiVersion);
        if (m.find()) {
            apiVersion = m.group();
            request.setAttribute(versionParam, apiVersion);
        } else {
            apiVersion = null;
        }
        return apiVersion;
    }

}
